package com.share.shareplatform.sharereward.config;


import com.share.shareplatform.pojo.exception.LogicException;
import com.share.shareplatform.util.Result;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;
import java.util.List;

@RestControllerAdvice
public class ExceptionConfig {

    //参数不匹配
    @ExceptionHandler({MethodArgumentNotValidException.class})
    public Result exceptionResult(MethodArgumentNotValidException e){
        BindingResult bindingResult = e.getBindingResult();

        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        String message = fieldErrors.get(0).getDefaultMessage();

        return Result.getInstance(200,message);
    }

    @ExceptionHandler({LogicException.class})
    public Result logicExceptionHandle(LogicException e){
        return Result.getInstance(505,e.getMessage());
    }

    @ExceptionHandler({Exception.class})
    public Result exceptionLogic(Exception e){

        return Result.getInstance(505,e.getMessage());
    }

    @ExceptionHandler({ConstraintViolationException.class})
    public Result methodParameterException(ConstraintViolationException e){
        String realError = e.getMessage().substring(e.getMessage().lastIndexOf(" ")+1, e.getMessage().length());
        return Result.getInstance(505,realError);
    }

    @ExceptionHandler({AccessDeniedException.class})
    public Result accessDeniedExceptionHandle(AccessDeniedException e){
        return Result.getInstance(505,"权限不足");
    }
}
